package com.test.tools;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

public class FormUtil {
	@SuppressWarnings("unchecked")
	public  static void fillForm(HttpServletRequest request, String formClassFullName,
			String formName){
		//1.创建一个actionform的实例
		//2.得到所有参数名 和属性名
		//3.匹配每一个客户端参数名字和每一个Form的属性名字
		//4.如果匹配就把值取出来 设置值到对应的Form属性
		//5.把form保存在Scope中
		try {
			//1.
			ActionForm form=(ActionForm)Class.forName(formClassFullName).newInstance();
			//2.
			Enumeration<String> parameterEnumeration = request.getParameterNames();
			Field[] fields = form.getClass().getDeclaredFields();
			//3.
			while(parameterEnumeration.hasMoreElements()){
				String parameterName = (String)parameterEnumeration.nextElement();
				for(Field field:fields){
					String fieldName = field.getName();
					//4.
					if(parameterName.equals(fieldName)){
						//4.1
						String value = request.getParameter(fieldName);
						try {
							org.apache.commons.beanutils.BeanUtils.setProperty(form, fieldName, value);
						} catch (InvocationTargetException e) {
							e.printStackTrace();
						}
					}
				}
			}
			//5.
			request.getSession().setAttribute(formName, form);
			
			System.out.println(form);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
